package demo6;

import java.util.concurrent.TimeUnit;

/*对业务写方法加锁，对业务读方法不加锁，容易产生脏读问题，读到在写的过程中还没有完成的数据，可以对读方法加锁*/
public class Account {
    private String name;
    private double balance; //账户余额为成员变量 默认为0.0

    public synchronized void set(String name, double balance) { //写
        this.name = name;
        try {
            Thread.sleep(2000); //2s
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.balance = balance;
    }

    public synchronized double getBalance(String name) {  //读
        return this.balance;
    }

    public static void main(String[] args) {
        Account a = new Account();
        new Thread(() -> a.set("张三", 100.0)).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(a.getBalance("张三"));  //0.0
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(a.getBalance("张三"));  //100.0
    }
}
